package dalex.client;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Event;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;

public class ClientFrame extends JFrame {
	private static final long serialVersionUID = 1L;
	private TextField tf = null ; 
	private JButton jb = null ; 
	 
	public ClientFrame(){
		initComponent() ;
	}
	
	private void initComponent() {
		this.setSize(500,500);
		this.setTitle("DALEX_MUD   "+Common.nickname);
		
		int x = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
		int y = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
		this.setLocation((x - this.getWidth()) / 2, (y-this.getHeight())/ 2);
		this.setResizable(false);
		
		Container container = this.getContentPane() ; 
		container.setLayout(new BorderLayout());
		
		Common.textArea = new TextArea(25,25) ; 
		this.tf = new TextField() ; 
		this.jb = new JButton("发送") ;
		
		jb.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e ){
				send() ;
			}
		});
		this.tf.addKeyListener(new KeyAdapter(){   
			public void keyPressed(KeyEvent e){   
				if(e.getKeyCode() == Event.ENTER){   
					send() ;
				}
			}   
		});
		this.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e) {
				Common.commandProxy.send("logout "+Common.nickname) ; 
				try {
					Common.socket.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				} 
				System.exit(0);
			}
		});
		
		container.add(Common.textArea , BorderLayout.NORTH) ;
		container.add(tf , BorderLayout.CENTER) ;
		container.add(jb , BorderLayout.SOUTH) ; 
		
		this.setVisible(true );
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
	}
	
	private void send() {
		Common.textArea.append(Common.nickname+":"+tf.getText()+"\n\n");
		Common.commandProxy.send(tf.getText()) ;
		tf.setText("");
	}
}
